package IO;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIO {

    public static void main(String[] args) throws IOException {
        //file channel=>buffer
        //打开文件 返回文件描述符
        RandomAccessFile aFile = new RandomAccessFile("/Users/huanggang/Projects/java/data-structure/src/IO/hello.txt", "rw");
        //创建文件描述channel
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48);

        //通过读channel查看buffer中的数据是否就绪
        //不阻塞 但是需要轮训查看
        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            System.out.println("Read " + bytesRead);
            //读模式转换成写模式
            buf.flip();

            while(buf.hasRemaining()){
                System.out.print((char) buf.get());
            }

            //清空缓冲区
            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        //关闭文件 释放文件描述符
        aFile.close();
    }
}
